package com.vm.fragment;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.vm.activity.BitmapCache;
import com.vm.activity.DetailActivity;
import com.vm.activity.UserInfoActivity;
import com.vm.adapter.FoundAdapter;
import com.vm.commons.StringUtil;
import com.vm.commons.VMConst;
import com.vm.model.ActiveSoft;
import com.vm.myview.FoundDown;
import com.vm.myview.ViewUtils;
import com.vm.utils.JsonUtils;
import com.vm.utils.SingleRequestQueue;
import com.wwt.app.R;

import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class FoundFragment extends BaseFragment {
	protected static final String TAG = "FoundActivity";

	private View view;
	private RequestQueue mQueue;
	ImageListener listener;
	ImageLoader mImageLoader;
	Button btn_recommended;
	Button btn_hot_game;
	Button btn_latest_application;
	Button btn_topical_application;
	Button btn_latest_game;
	Button btn_recommend_online_game;
	ViewUtils viewUtils;

	/** 标志位，标志已经初始化完成 */
	private boolean isPrepared;
	/** 是否已被加载过一次，第二次就不再去请求数据了 */
	private boolean mHasLoadedOnce;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		Log.i("FoundFragment", "onCreateView");

		if (view == null) {
			view = inflater.inflate(R.layout.found, null);
		} else {
			// 缓存的rootView需要判断是否已经被加过parent
			// 如果有parent需要从parent删除
			ViewGroup parent = (ViewGroup) view.getParent();
			if (parent != null) {
				parent.removeView(view);
			}
		}

		isPrepared = true;
		lazyLoad();

		// = inflater.inflate(R.layout.found, null);
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		Log.i("FoundFragment", "onActivityCreated");

	}

	OnItemClickListener gd_listener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {

			Intent intent = new Intent(getActivity(), DetailActivity.class);
			TextView textView = (TextView) view.findViewById(R.id.tv_softName);
			String softId = textView.getTag().toString();
			intent.putExtra("softId", softId);
			startActivityForResult(intent, 10);

		}
	};

	/**
	 * 初始化登录
	 */
	public static void login(ImageView iv_logo) {

		iv_logo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(v.getContext(),
						UserInfoActivity.class);
				v.getContext().startActivity(intent);
			}
		});
	}

	/**
	 * 下载按钮监听
	 */
	public OnClickListener downClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {

			Button btn_soft_download = (Button) v;

			if (btn_soft_download.getText().toString().equals("已安装")) {
				// 不做任何操作
			} else if (btn_soft_download.getText().toString().toString()
					.equals("安装")) {
				// 执行安装
				Toast toast3 = Toast.makeText(getActivity(), "正在安装", 500);
				toast3.setGravity(Gravity.CENTER, 0, 0);
				toast3.show();
				btn_soft_download.setText("正在安装");

				File apkfile = new File(
						StringUtil.getSdApkUrl(btn_soft_download.getTag()
								.toString()));
				if (!apkfile.exists()) {
					return;
				}
				Intent i = new Intent(Intent.ACTION_VIEW);
				i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
						"application/vnd.android.package-archive");
				startActivity(i);

			} else {

				// 下载APK
				// layout_collect.setVisibility(View.GONE);
				// layout_share.setVisibility(View.GONE);
				// layout_pause.setVisibility(View.VISIBLE);
				// layout_cancel.setVisibility(View.VISIBLE);
				// btn_soft_download.setVisibility(View.GONE);
				//
				// layout_pause.setOnClickListener(layout_pauseClickListener);
				//
				// progressBar1.setVisibility(View.VISIBLE);
				// currentId = v.getTag().toString();
				// Log.i(TAG, currentId);
				// System.out
				// .println("<<<<" + nowProgressValue + "<<<" + fileSize);
				// progressText.setText("稍等");
				// progressText.setTextColor(Color.BLACK);
				// Message msg = new Message();
				// // msg.arg1 = currentId;
				// msg.what = 100;
				// // 下载地址
				// // msg.obj = VMConst.DOWN_URL + currentId + "&userId="
				// // + CurrentUser.USERID;
				// msg.obj = soft;
				// downThread = new DownloadThread(getApplicationContext(),
				// mainHandler);
				// downThread.start();
				//
				// do {
				// downHandler = downThread.getDownHandler();
				// } while (null == downHandler);
				//
				// downHandler.sendMessage(msg);
			}

		}
	};

	@Override
	protected void lazyLoad() {

		Log.i("FoundFragment", "lazyLoad");
		Log.i("lazyLoad", "isPrepared=" + isPrepared + ",isVisible="
				+ isVisible + ",mHasLoadedOnce=" + mHasLoadedOnce);
		// TODO Auto-generated method stub
		if (!isPrepared || !isVisible || mHasLoadedOnce) {
			return;
		}
		Log.i("FoundFragment", "lazyLoad--AsyncTask");
		new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				// 显示加载进度对话框
				UIHelper.showDialogForLoading(getActivity(), "正在加载...", true);
			}

			@Override
			protected Boolean doInBackground(Void... params) {
				try {
					Thread.sleep(1000);
					// 在这里添加调用接口获取数据的代码
					initData();
					// doSomething()
				} catch (Exception e) {
					e.printStackTrace();
				}
				return true;
			}

			@Override
			protected void onPostExecute(Boolean isSuccess) {
				if (isSuccess) {
					// 加载成功
					
					mHasLoadedOnce = true;
				} else {
					// 加载失败
				}
				// 关闭对话框
				UIHelper.hideDialogForLoading();
			}
		}.execute();

	}

	public void initData() {
		// initBtn();
		mQueue = SingleRequestQueue.getRequestQueue(getActivity());
		viewUtils = new ViewUtils(getActivity());

		initData1();

	}

	public void initData1() {
		/**
		 * EP环境保护
		 */
		JsonArrayRequest json_EP = new JsonArrayRequest(
				"http://www.91pcapp.com/json/getEP", new Listener<JSONArray>() {
					@Override
					public void onResponse(JSONArray arg0) {

						JSONObject jsonObject;
						for (int i = 0; i < arg0.length(); i++) {
							try {
								jsonObject = arg0.getJSONObject(i);
								final ActiveSoft activeSoft = JsonUtils
										.jsonToBean(jsonObject,
												ActiveSoft.class);

								LinearLayout found_ll_1 = (LinearLayout) view
										.findViewById(R.id.found_ll_1);

								// LinearLayout linearLayout = dyAddView(i,
								// activeSoft);
								found_ll_1.addView(viewUtils.dyAddView(i,
										activeSoft, 1));

							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
						jsonObject = null;
						
						initData2();
					}

				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						// Log.e(TAG, error.getMessage(), error);
					}
				});
		mQueue.add(json_EP);
		json_EP = null;
	}

	public void initData2() {
		/**
		 * LCU 生活常用
		 */

		JsonArrayRequest json_LCU = new JsonArrayRequest(
				"http://www.91pcapp.com/json/getLCU",
				new Listener<JSONArray>() {
					@Override
					public void onResponse(JSONArray arg0) {
						JSONObject jsonObject;
						ActiveSoft activeSoft;
						List<ActiveSoft> list_LCU = new ArrayList<ActiveSoft>();
						for (int i = 0; i < arg0.length(); i++) {
							try {
								jsonObject = arg0.getJSONObject(i);
								activeSoft = JsonUtils.jsonToBean(jsonObject,
										ActiveSoft.class);

								list_LCU.add(activeSoft);

							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}

						FoundAdapter adapter = new FoundAdapter(getActivity(),
								list_LCU);
						GridView gridView = (GridView) view
								.findViewById(R.id.gv_LCU);
						gridView.setFocusable(false);
						gridView.setOnItemClickListener(gd_listener);
						gridView.setAdapter(adapter);

						activeSoft = null;
						jsonObject = null;
						list_LCU = null;
						adapter = null;
						
						initData3();
					}

				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						// Log.e(TAG, error.getMessage(), error);
					}
				});

		mQueue.add(json_LCU);
	}

	public void initData3() {
		/**
		 * JobSearch找工作
		 */
		JsonArrayRequest json_JobSearch = new JsonArrayRequest(
				"http://www.91pcapp.com/json/getJobSearch",
				new Listener<JSONArray>() {
					@Override
					public void onResponse(JSONArray arg0) {
						JSONObject jsonObject;
						ActiveSoft activeSoft;
						int count = arg0.length();
						for (int i = 0; i < count; i++) {
							try {
								jsonObject = arg0.getJSONObject(i);
								activeSoft = JsonUtils.jsonToBean(jsonObject,
										ActiveSoft.class);

								LinearLayout found_ll_2 = (LinearLayout) view
										.findViewById(R.id.found_ll_2);

								found_ll_2.addView(viewUtils.dyAddView(i,
										activeSoft, 1));

							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
						activeSoft = null;
						jsonObject = null;
						initData4();
					}

				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						// Log.e(TAG, error.getMessage(), error);
					}
				});

		mQueue.add(json_JobSearch);
		json_JobSearch = null;

	}

	public void initData4() {
		/**
		 * WG精彩游戏
		 */

		JsonArrayRequest json_WG = new JsonArrayRequest(
				"http://www.91pcapp.com/json/getWG", new Listener<JSONArray>() {
					@Override
					public void onResponse(JSONArray arg0) {
						int count = arg0.length();
						JSONObject jsonObject = null;
						ActiveSoft activeSoft;
						List<ActiveSoft> list_WG = new ArrayList<ActiveSoft>();
						for (int i = 0; i < count; i++) {
							try {
								jsonObject = arg0.getJSONObject(i);
								activeSoft = JsonUtils.jsonToBean(jsonObject,
										ActiveSoft.class);

								list_WG.add(activeSoft);

							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}

						FoundAdapter adapter = new FoundAdapter(getActivity(),
								list_WG);
						GridView gridView = (GridView) view
								.findViewById(R.id.gv_WG);
						gridView.setFocusable(false);
						gridView.setOnItemClickListener(gd_listener);
						gridView.setAdapter(adapter);

						jsonObject = null;
						adapter = null;
						list_WG = null;
						activeSoft = null;
						initData5();
					}

				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						// Log.e(TAG, error.getMessage(), error);
					}
				});

		mQueue.add(json_WG);
		json_WG = null;
	}

	public void initData5() {
		/**
		 * CF聊天交友
		 */
		JsonArrayRequest json_CF = new JsonArrayRequest(
				"http://www.91pcapp.com/json/getCF", new Listener<JSONArray>() {
					@Override
					public void onResponse(JSONArray arg0) {

						JSONObject jsonObject;
						int count = arg0.length();
						ActiveSoft activeSoft;
						for (int i = 0; i < count; i++) {
							try {
								jsonObject = arg0.getJSONObject(i);
								activeSoft = JsonUtils.jsonToBean(jsonObject,
										ActiveSoft.class);

								LinearLayout found_ll_3 = (LinearLayout) view
										.findViewById(R.id.found_ll_3);

								found_ll_3.addView(viewUtils.dyAddView(i,
										activeSoft, 1));

							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}

						activeSoft = null;
						jsonObject = null;

						initData6();
					}

				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						// Log.e(TAG, error.getMessage(), error);
					}
				});

		mQueue.add(json_CF);
		json_CF = null;
	}

	public void initData6() {
		/**
		 * WG理财支付
		 */

		JsonArrayRequest json_FP = new JsonArrayRequest(
				"http://www.91pcapp.com/json/getFP", new Listener<JSONArray>() {
					@Override
					public void onResponse(JSONArray arg0) {

						int count = arg0.length();
						JSONObject jsonObject;
						ActiveSoft activeSoft;
						List<ActiveSoft> list_FP = new ArrayList<ActiveSoft>();
						for (int i = 0; i < count; i++) {
							try {
								jsonObject = arg0.getJSONObject(i);
								activeSoft = JsonUtils.jsonToBean(jsonObject,
										ActiveSoft.class);

								list_FP.add(activeSoft);

							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}

						FoundAdapter adapter = new FoundAdapter(getActivity(),
								list_FP);
						GridView gridView = (GridView) view
								.findViewById(R.id.gv_FP);
						gridView.setFocusable(false);
						gridView.setOnItemClickListener(gd_listener);
						gridView.setAdapter(adapter);

						list_FP = null;
						adapter = null;
						activeSoft = null;

						initData7();
					}

				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						// Log.e(TAG, error.getMessage(), error);
					}
				});

		mQueue.add(json_FP);
		json_FP = null;
	}

	public void initData7() {
		/**
		 * TT交通旅游
		 */
		JsonArrayRequest json_TT = new JsonArrayRequest(
				"http://www.91pcapp.com/json/getTT", new Listener<JSONArray>() {
					@Override
					public void onResponse(JSONArray arg0) {
						JSONObject jsonObject;
						ActiveSoft activeSoft;
						int count = arg0.length();
						for (int i = 0; i < count; i++) {
							try {
								jsonObject = arg0.getJSONObject(i);
								activeSoft = JsonUtils.jsonToBean(jsonObject,
										ActiveSoft.class);

								LinearLayout found_ll_4 = (LinearLayout) view
										.findViewById(R.id.found_ll_4);

								found_ll_4.addView(viewUtils.dyAddView(i,
										activeSoft, 1));

							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}

						jsonObject = null;
						activeSoft = null;

						initData8();
					}

				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						// Log.e(TAG, error.getMessage(), error);
					}
				});

		mQueue.add(json_TT);
		json_TT = null;
	}

	public void initData8() {
		/**
		 * ETM娱乐应用
		 */

		JsonArrayRequest json_ETM = new JsonArrayRequest(
				"http://www.91pcapp.com/json/getETM",
				new Listener<JSONArray>() {
					@Override
					public void onResponse(JSONArray arg0) {
						List<ActiveSoft> list_ETM = new ArrayList<ActiveSoft>();
						JSONObject jsonObject;
						ActiveSoft activeSoft;
						int count = arg0.length();
						for (int i = 0; i < count; i++) {
							try {
								jsonObject = arg0.getJSONObject(i);
								activeSoft = JsonUtils.jsonToBean(jsonObject,
										ActiveSoft.class);

								list_ETM.add(activeSoft);

							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}

						FoundAdapter adapter = new FoundAdapter(getActivity(),
								list_ETM);
						GridView gridView = (GridView) view
								.findViewById(R.id.gv_ETM);
						gridView.setFocusable(false);
						gridView.setOnItemClickListener(gd_listener);
						gridView.setAdapter(adapter);

						adapter = null;
						jsonObject = null;
						activeSoft = null;
						list_ETM = null;

					}

				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						// Log.e(TAG, error.getMessage(), error);
					}
				});

		mQueue.add(json_ETM);
		json_ETM = null;
	}
}
